import React, { PureComponent } from "react";
import { View, StyleSheet, Text, SafeAreaView, ScrollView, TextInput, ToastAndroid } from "react-native";
import { Button, Icon } from "react-native-tengits-elements";
import DataCenter from "../logic/DataCenter";
import { scaleSize } from "../common/Utils/ToolUtils";
import { Colors, FontSize } from "../common/Theme/TTheme";
import CommonDrawer from "../common/Widgets/CommonDrawer";
import _ from 'lodash';
import { Loop_Device_Base, RS_Device_Type } from "../libs/SerialCommon";
import { CircuitItem2 } from "./Components/SubItemComponent";
import { DevicePort, InterfaceType, MeterConfig, ProductID, SerialConfig } from "../logic/LogicConstant";
import LoadingUtil from "../common/Utils/LoadingUtil";
import SerialPortManager from "../logic/SerialPortManager";
import XLog from "../libs/XLog";
import {parserSmartMeter} from "../libs/SerialMeterParser";

export default class DebugDevicePage extends React.PureComponent {
    constructor(props) {
        super(props);
        let smartMeterChannels = {};
        for(let smart of DataCenter.smartMeterList||[]) {
            smartMeterChannels[smart.index] = [{name:"通道1："}, {name:"通道2："}, {name:"通道3："}, {name:"通道4："}];
        }
        this.state = {
            localCabinet: DataCenter.getLocalCabinetData(),
            smartMeterChannels: smartMeterChannels,
            loopControllerState:{},
            smartMeterState:{},
        };
        this.LoopControllerAddress = {};
        this.SmartMeterAddress = {};
    }

    componentDidMount() {
        this.bindOnQueryDeviceAddress = this.onQueryDeviceAddress.bind(this);
        SerialPortManager.addSerialEvent(
            "readAddress",
            this.bindOnQueryDeviceAddress,
        );

        this.bindOnSetLampState = this.onSetLampState.bind(this);
        SerialPortManager.addSerialEvent(
            "setLampState",
            this.bindOnSetLampState,
        );

        this.bindOnSetLampLight = this.onSetLampLight.bind(this);
        SerialPortManager.addSerialEvent(
            "setLampLight",
            this.bindOnSetLampLight
        );

        this.bindOnQueryDeviceInfo = this.onQueryDeviceInfo.bind(this)
        SerialPortManager.addSerialEvent(
            "readLight",
            this.bindOnQueryDeviceInfo
        );

        this.bindOnSerialTimeout = this.onSerialTimeout.bind(this);
        SerialPortManager.addSerialEvent(
            "timeout",
            this.bindOnSerialTimeout
        );

        this.bindOnMeterRealtime = this.onMeterRealtime.bind(this);
        SerialPortManager.addSerialEvent(
            "realtime",
            this.bindOnMeterRealtime,
        );

        this.bindOnMeterStat = this.onMeterStat.bind(this);
        SerialPortManager.addSerialEvent(
            "stat",
            this.bindOnMeterStat,
        );
    }

    componentWillUnmount() {
        SerialPortManager.removeSerialEvent("readAddress",this.bindOnQueryDeviceAddress);

        SerialPortManager.removeSerialEvent("setLampState",this.bindOnSetLampState);

        SerialPortManager.removeSerialEvent("setLampLight", this.bindOnSetLampLight);

        SerialPortManager.removeSerialEvent("readLight", this.bindOnQueryDeviceInfo);

        SerialPortManager.removeSerialEvent("timeout", this.bindOnSerialTimeout);

        SerialPortManager.removeSerialEvent("realtime", this.bindOnMeterRealtime);

        SerialPortManager.removeSerialEvent("stat", this.bindOnMeterStat);
    }

    onQueryDeviceAddress(data){
        XLog.i("onQueryDeviceAddress data: " + JSON.stringify(data));
    }

    onSetLampLight(data){
        // DataCenter.setLightLight(data);
        XLog.i("onSetLampLight data: " + JSON.stringify(data));
    }

    onSetLampState(data){
        // DataCenter.setLightState(data);
        XLog.i("setLightState data: " + JSON.stringify(data));
    }

    onQueryDeviceInfo(data){
        LoadingUtil.dismissLoading();
        DataCenter.updateLocalCabinetLoops(data);
        this.setState({
            localCabinet: DataCenter.getLocalCabinetData(),
        });
    }

    onSerialTimeout(data){
        LoadingUtil.dismissLoading();
        DataCenter.updateInvalidState(data);
        this.setState({
            localCabinet: DataCenter.getLocalCabinetData(),
        });
    }

    filterSmartList(realtime, property, channel){
        if(realtime == null || realtime[property] == null){
            return [];
        }
        return realtime[property].filter(item => {
            return item.channel == channel;
        })
    }

    onMeterRealtime(data){
        try{
            LoadingUtil.dismissLoading();
            let smartMeterChannels = Object.assign({}, this.state.smartMeterChannels);
            let smartMeterList = parserSmartMeter(data.message);
            if(smartMeterList.realtime && Object.keys(smartMeterList.realtime).length > 0){
                let realtime = smartMeterList.realtime;
                for(var i = 0; i < 4; i++){
                    smartMeterChannels[data.index][i] = {name: "通道" + (i+1) + ": 电压: ["};
                    let vol_channel = this.filterSmartList(realtime, "voltage", i+1);
                    if(vol_channel && vol_channel.length > 0){
                        smartMeterChannels[data.index][i].name += vol_channel[0]["a"] + ",";
                        smartMeterChannels[data.index][i].name += vol_channel[0]["b"] + ",";
                        smartMeterChannels[data.index][i].name += vol_channel[0]["c"] + "] 电流:[";
                    }
                    let current_channel = this.filterSmartList(realtime, "current", i+1);
                    if(current_channel && vol_channel.length > 0){
                        smartMeterChannels[data.index][i].name += current_channel[0]["a"] + ",";
                        smartMeterChannels[data.index][i].name += current_channel[0]["b"] + ",";
                        smartMeterChannels[data.index][i].name += current_channel[0]["c"] + "]";
                    }
                }
                this.setState({
                    smartMeterChannels: smartMeterChannels
                })
            }
        }catch(error) {
            console.log("DebugDevicePage onMeterRealtime exception:", error?.message);
        }
    }

    onMeterStat(data){
        console.log("DebugDevicePage onMeterStat:", data);
    }

    renderHeader() {
        return <View style={styles.header}>
                <Button 
                    buttonStyle={{borderRadius:0, backgroundColor:Colors.button_color, width:scaleSize(117), height:scaleSize(88)}} 
                    icon={<Icon name='menu' color={Colors.white} size={scaleSize(40)}/>}
                    onPress={()=>{
                        this.selectDrawer && this.selectDrawer.showModalAnimate()
                }}/>
                <View style={{flex:1, flexDirection:'row', alignItems:'center', justifyContent:'center'}}>
                    <Text style={{fontSize: FontSize.h4_font, color:Colors.white}}>{"本柜"}</Text>
                </View>
        </View>
    }

    sliderCallback = (loopItem, value) =>{
        //UICommandExecute.onLocalRealSlider([loopItem.loopNumber], value);
    }

    sliderCompleteCallback = (loopItem, value) =>{
        //UICommandExecute.onLocalSliderComplete([loopItem.loopNumber], value, true);
        SerialPortManager.controlLight(loopItem.loopNumber, value);
        SerialPortManager.controlLightEnd();
    }

    renderMenuDrawer() {
        const{navigation} = this.props;
        return <View style={{flex:1, flexDirection:'column', justifyContent:'space-between', paddingHorizontal:scaleSize(44)}}>
                <Button buttonStyle={{height:scaleSize(88), backgroundColor:Colors.button_color}} 
                    titleStyle={{fontSize: FontSize.h4_font}}
                    title={"本控制柜管控"} onPress={()=>{
                    this.selectDrawer && this.selectDrawer.hideModalAnimate();
                    navigation.replace('Main');
                }}/>
                <Button buttonStyle={{marginTop:scaleSize(30), height:scaleSize(88), backgroundColor:Colors.button_color}} 
                    titleStyle={{fontSize: FontSize.h4_font}}
                    title={"集群控制柜管控"} onPress={()=>{
                    this.selectDrawer && this.selectDrawer.hideModalAnimate();
                    navigation.replace('Colony')
                }}/>
                <Button buttonStyle={{marginTop:scaleSize(30), height:scaleSize(88), backgroundColor:Colors.button_color}}
                    titleStyle={{fontSize: FontSize.h4_font}}
                    title={"单洞分段调控"} onPress={()=>{
                    this.selectDrawer && this.selectDrawer.hideModalAnimate();
                    navigation.replace('SingleHole')
                }}/>
                <Button buttonStyle={{marginTop:scaleSize(30), height:scaleSize(88), backgroundColor:Colors.button_color}} 
                    titleStyle={{fontSize: FontSize.h4_font}}
                    title={"控制柜运行概览"} onPress={()=>{
                    this.selectDrawer && this.selectDrawer.hideModalAnimate();
                    navigation.replace('DeviceSummary')
                }}/>
                <Button buttonStyle={{marginTop:scaleSize(30), height:scaleSize(88), backgroundColor:Colors.button_color}}
                    titleStyle={{fontSize: FontSize.h4_font}}
                    title={"设备信息"} onPress={()=>{
                    this.selectDrawer && this.selectDrawer.hideModalAnimate();
                    navigation.replace('DeviceInfo')
                }}/>
                <Button buttonStyle={{marginTop:scaleSize(30), height:scaleSize(88), backgroundColor:Colors.button_color}}
                    titleStyle={{fontSize: FontSize.h4_font}}
                    title={"注册管理"} onPress={()=>{
                    this.selectDrawer && this.selectDrawer.hideModalAnimate();
                    navigation.replace('RegisterDevice')
                }}/>
            </View>
    }

    render() {
        return <SafeAreaView style={styles.container}>
                {this.renderHeader()}
                <View style={{flex:1, flexDirection:'row'}}>
                    <View style={{flex:0.6}}>
                    {this.renderLoopController()}
                    </View>
                    <View style={{flex:0.4}}>
                    {this.renderSmartMeter()}
                    </View>
                </View>
                <CommonDrawer ref={(r) => {
                        this.selectDrawer = r;
                    }} contentView={this.renderMenuDrawer()}/>
            </SafeAreaView>
    }

    renderLoopController() {
        const{localCabinet, loopControllerState} = this.state;
        const group_data = _.groupBy(localCabinet?.loop||[], (item)=>Math.ceil(item.loopNumber/Loop_Device_Base));
        const keys = Object.keys(group_data||{})||[];
        return <ScrollView style={{flex:1}}>
            {keys.map((controllerNumber)=>{
                return <View key={"debug_loop_controller_" + controllerNumber} style={{flex:1, flexDirection:'column', marginBottom:scaleSize(30)}}>
                        <Text style={{color:Colors.text1_color, fontSize: FontSize.h3_font}}>{"回路控制器"+controllerNumber}</Text>
                        <View style={{flexDirection:'row', alignItems:'center'}}>
                            <Text style={{color:Colors.text1_color, fontSize: FontSize.h3_font}}>{"设备通讯地址:"}</Text>
                            <TextInput
                                style={styles.input}
                                defaultValue={this.LoopControllerAddress?.[controllerNumber]||""}
                                placeholder='请输入'
                                onChangeText={(value)=>{
                                    this.LoopControllerAddress[controllerNumber] = value;
                                }}
                                />
                            <Button buttonStyle={styles.sureBtn} 
                                title={loopControllerState[controllerNumber] == 0 ? "重新连接" : "连接"}
                                titleStyle={{fontSize: FontSize.h4_font}}
                                onPress={async()=>{
                                    let address = this.LoopControllerAddress?.[controllerNumber];
                                    if(!address) {
                                        ToastAndroid.show("请先输入设备通讯地址", ToastAndroid.SHORT);
                                    } else {
                                        let loopControllerState = this.state.loopControllerState;
                                        let dev = {id: controllerNumber, index: controllerNumber, key:"2",
                                                    address: address, type: RS_Device_Type.LOOP_4WAY, 
                                                    option: {...SerialConfig, port: DevicePort.LOOPCONTROLLER_PORT}, interface: InterfaceType.USB_SERIAL};
                                        LoadingUtil.showLoading();
                                        try{
                                            //await SerialPortManager.removeProductDevice(ProductID.LOOP, controllerNumber);
                                            await SerialPortManager.createDevice(ProductID.LOOP, dev, ()=>{
                                                loopControllerState[controllerNumber] = 0;
                                                this.setState({
                                                    loopControllerState:loopControllerState
                                                });
                                                SerialPortManager.sendLoopControllerRequest({"event": "readLight"}, controllerNumber);
                                                //ToastAndroid.show(`回路控制器${controllerNumber}连接成功`, ToastAndroid.SHORT);
                                            }, ()=>{
                                                loopControllerState[controllerNumber] = -1;
                                                this.setState({
                                                    loopControllerState:loopControllerState
                                                });
                                                LoadingUtil.dismissLoading();
                                                ToastAndroid.show(`回路控制器${controllerNumber}连接失败`, ToastAndroid.SHORT);
                                            })
                                        }catch(error) {
                                            loopControllerState[controllerNumber] = -1;
                                            this.setState({
                                                loopControllerState:loopControllerState
                                            });
                                            LoadingUtil.dismissLoading();
                                            ToastAndroid.show(`回路控制器${controllerNumber}连接异常`, ToastAndroid.SHORT);
                                        }
                                    }
                            }}/>
                        </View>
                        <View style={{marginTop:scaleSize(20)}}>
                            {(group_data[controllerNumber]||[]).map((loop, index)=>{
                                return <CircuitItem2 key={`${loop.loopName + "_" + index}`}
                                        containerStyle={{width:scaleSize(800)}}
                                        light={loop?.loopCurrentValue} 
                                        title={loop.loopName}
                                        callback={(value)=>this.sliderCallback(loop, value)}
                                        slideComplete={(value)=>this.sliderCompleteCallback(loop, value)}
                                        />
                            })}
                        </View>
                    </View>
            })}
        </ScrollView>
    }

    renderSmartMeter() {
        const{smartMeterChannels, smartMeterState} = this.state;
        return <ScrollView style={{flex:1}}>
            {(DataCenter.smartMeterList||[]).map((smartMeter)=>{
                return <View key={"debug_smart_" + smartMeter.index} style={{flex:1, flexDirection:'column', marginBottom:scaleSize(30)}}>
                        <Text style={{color:Colors.text1_color, fontSize: FontSize.h3_font}}>{"智能电表"+smartMeter.index}</Text>
                        <View style={{flexDirection:'row', alignItems:'center'}}>
                            <Text style={{color:Colors.text1_color, fontSize: FontSize.h3_font}}>{"设备通讯地址:"}</Text>
                            <TextInput
                                style={[styles.input,{width:scaleSize(140)}]}
                                defaultValue={this.SmartMeterAddress[smartMeter.index]||""}
                                placeholder='请输入'
                                onChangeText={(value)=>{
                                    this.SmartMeterAddress[smartMeter.index] = value;
                                }}
                                />
                            <Button buttonStyle={styles.sureBtn} 
                                title={smartMeterState[smartMeter.index] == 0 ? "重新连接" : "连接"}
                                titleStyle={{fontSize: FontSize.h4_font}}
                                onPress={async()=>{
                                    let address = this.SmartMeterAddress?.[smartMeter.index];
                                    if(!address) {
                                        ToastAndroid.show("请先输入设备通讯地址", ToastAndroid.SHORT);
                                    } else {
                                            let smartState = smartMeterState;
                                            let dev = {id: smartMeter.index, key:"3", index: smartMeter.index, 
                                                address: address, type: RS_Device_Type.METER, 
                                                option: {...MeterConfig, port: DevicePort.SMART_PORT}, interface: InterfaceType.USB_SERIAL};
                                            LoadingUtil.showLoading();
                                            try{
                                                //await SerialPortManager.removeProductDevice(ProductID.SMART, smartMeter.index);
                                                await SerialPortManager.createDevice(ProductID.SMART, dev, ()=>{
                                                    //ToastAndroid.show(`智能电表${smartMeter.index}连接成功`, ToastAndroid.SHORT);
                                                    smartState[smartMeter.index] = 0;
                                                    this.setState({
                                                        smartMeterState: smartState
                                                    });
                                                    SerialPortManager.sendMeterRequest(smartMeter.index);
                                                }, ()=>{
                                                    smartState[smartMeter.index] = -1;
                                                    this.setState({
                                                        smartMeterState: smartState
                                                    });
                                                    LoadingUtil.dismissLoading();
                                                    ToastAndroid.show(`智能电表${smartMeter.index}连接失败`, ToastAndroid.SHORT);
                                                })
                                            }catch(error) {
                                                smartState[smartMeter.index] = -1;
                                                this.setState({
                                                    smartMeterState: smartState
                                                });
                                                LoadingUtil.dismissLoading();
                                                ToastAndroid.show(`智能电表${smartMeter.index}连接异常`, ToastAndroid.SHORT);
                                            }
                                    }
                            }}/>
                        </View>
                        <View style={{marginTop:scaleSize(20)}}>
                        {(smartMeterChannels[smartMeter.index]||[]).map((smartChannel, index)=>{
                            return <View key={"smart_channel_" + index} style={{flexDirection:'row'}}>
                                <Text style={{color:Colors.text1_color, fontSize: FontSize.h4_font}}>{smartChannel.name}</Text>
                            </View>
                        })}
                        </View>
                    </View>
            })}
        </ScrollView>
    }
}

const styles = StyleSheet.create({
    container:{
        flex:1, 
        backgroundColor: Colors.page_bg_color, 
        justifyContent:'space-around'
    },
    header:{
        flexDirection: 'row',
        height: scaleSize(88),
        backgroundColor: Colors.navibar_color,
    },
    input:{
        fontSize: FontSize.h3_font,
        marginLeft:scaleSize(10), 
        backgroundColor:'#F5F5FF', 
        width:scaleSize(240), 
        height:scaleSize(64),
        paddingVertical:0,
        borderWidth:1, 
        borderColor: Colors.border_color
    },
    sureBtn:{
        paddingVertical:0, 
        marginLeft:scaleSize(30), 
        backgroundColor: Colors.button_color, 
        width:scaleSize(180), 
        height:scaleSize(64)
    }
});